﻿using AutoMapper;
using MediatR;
using ProduceBasicData.Api.Application.Command.RBAC.Permission;
using ProduceBasicData.Api.DTO.RBACDto;
using ProduceBasicData.Domain.RBAC;
using ProduceBasicData.ErrorCode;
using ProduceBasicData.Infrastructure.Interface;

namespace ProduceBasicData.Api.Application.Handler.RBAC.Permission
{
    /// <summary>
    /// 获取所有权限的处理器（不分页）
    /// </summary>
    public class GetAllPermissionHandler : IRequestHandler<GetAllPermissionCommand, ApiResult<List<PermissionsDto>>>
    {
        private readonly IBaseRespository<PermissionModel> _PermissionRepository;
        private readonly IMapper _mapper;

        public GetAllPermissionHandler(IBaseRespository<PermissionModel> PermissionRepository, IMapper mapper)
        {
            _PermissionRepository = PermissionRepository;
            _mapper = mapper;
        }

        public async Task<ApiResult<List<PermissionsDto>>> Handle(GetAllPermissionCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<List<PermissionsDto>>();

            try
            {
                // 查询所有「未删除」的权限
                var Permissions = await _PermissionRepository.GetAllAsync();
                var query = Permissions.Where(x => x.Isdel == false);

                // 映射为 DTO 列表
                var PermissionDtos = query.Select(x => new PermissionsDto
                {
                    Id = x.Id,
                    PermissionName = x.PermissionName,
                    PermissionCode = x.PermissionCode,
                    ParentId = x.ParentId,
                    Path = x.Path,
                    Icon = x.Icon,
                    PermissionType = x.PermissionType,
                    Sort = x.Sort,
                    State = x.State,
                    CreateName = x.CreateName,
                    CreateTime = x.CreateTime,
                    UpdateName = x.UpdateName,
                    UpdateTime = x.UpdateTime,
                    Isdel = x.Isdel
                }).ToList();

                result.Data = PermissionDtos;
                result.Code = ApiEnum.Success;
                result.Msg = "查询所有权限成功";
            }
            catch (Exception ex)
            {
                result.Code = ApiEnum.Failed;
                result.Msg = $"查询异常: {ex.Message}";
                result.Data = new List<PermissionsDto>();
            }

            return result;
        }
    }
}
